﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;

namespace DesertedRoadStudios.BlogNetNuke
{
    public static class Extensions
    {
        public static UserControl LoadControl(this TemplateControl templateControl, string controlPath, params object[] constructorParams)
        {
            // Load the control
            var control = templateControl.LoadControl(controlPath) as UserControl;

            // Get the types for the passed parameters
            Type[] paramTypes = new Type[constructorParams.Length];
            for (int paramLoop = 0; paramLoop < constructorParams.Length; paramLoop++)
            {
                paramTypes[paramLoop] = constructorParams[paramLoop].GetType();
            }

            // Get the constructor that matches our signature
            var constructor = control.GetType().BaseType.GetConstructor(paramTypes);

            // Call the constructor if we found it, otherwise throw
            if (constructor == null)
            {
                throw new ArgumentException("Required constructor signature not found.");
            }
            else
            {
                constructor.Invoke(control, constructorParams);
            }

            return control;
        }

        public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
        {
            Random r = new Random();

            return target.OrderBy(x => (r.Next()));
        }
    }
}